const Router = require('koa-router');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const db = require('../models/db');
const config = require('../config');

const router = new Router();
const SALT_ROUNDS = 10;

// 用户注册
router.post('/register', async (ctx) => {
  const { username, password } = ctx.request.body;
  if (!username || !password) {
    ctx.status = 400;
    ctx.body = { error: 'Username and password are required' };
    return;
  }

  try {
    const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
    const result = await db.query(
      'INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING id, username',
      [username, hashedPassword]
    );
    ctx.status = 201;
    ctx.body = { user: result.rows[0] };
  } catch (err) {
    if (err.code === '23505') { // Unique violation
      ctx.status = 409;
      ctx.body = { error: 'Username already exists' };
    } else {
      ctx.status = 500;
      ctx.body = { error: 'Internal server error' };
      console.error('Error during registration:', err);
    }
  }
});

// 用户登录
router.post('/login', async (ctx) => {
  const { username, password } = ctx.request.body;
  if (!username || !password) {
    ctx.status = 400;
    ctx.body = { error: 'Username and password are required' };
    return;
  }

  try {
    const result = await db.query('SELECT * FROM users WHERE username = $1', [username]);
    if (result.rows.length === 0) {
      ctx.status = 401;
      ctx.body = { error: 'Invalid username or password' };
      return;
    }

    const user = result.rows[0];
    const passwordMatch = await bcrypt.compare(password, user.password_hash);

    if (!passwordMatch) {
      ctx.status = 401;
      ctx.body = { error: 'Invalid username or password' };
      return;
    }

    const token = jwt.sign({ id: user.id, username: user.username }, config.jwtSecret, {
      expiresIn: '1h', // Token expires in 1 hour
    });

    ctx.body = { token };
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error during login:', err);
  }
});

module.exports = router;
